﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;

namespace Multiprocessing.Core.Units
{
    public class WorkerProcessingUnit : BaseProcessingUnit
    {
        #region Fields

        private bool _disposed;
        private readonly BackgroundWorker _backgroundWorker;
        private readonly AutoResetEvent _autoResetEvent;

        #endregion

        #region Properties

        public override bool IsRunning
        {
            get { return _backgroundWorker.IsBusy; }
        }

        #endregion

        #region Constructors

        public WorkerProcessingUnit()
        {
            _backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true };
            _backgroundWorker.DoWork += (s, e) => Action();
            _backgroundWorker.RunWorkerCompleted += (s, e) =>
            {
                _autoResetEvent.Set();
                OnFinished();
            };
            _autoResetEvent = new AutoResetEvent(false);
        }

        #endregion

        #region Methods

        public override void Start()
        {
            _backgroundWorker.RunWorkerAsync();
        }

        public override void ForceStop()
        {
            _backgroundWorker.CancelAsync();
        }

        public override void Wait()
        {
            _autoResetEvent.WaitOne();
        }
        
        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _backgroundWorker.Dispose();
                }
                _disposed = true;
            }
            base.Dispose(disposing);
        }
        #endregion
    }
}
